package WiFi;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import peer.PeerManager;

import client.ClientConnectable;
import exception.NFCException;

public class WiFiServerThread extends Thread {

	private static final int PORT = 4432;
	private static final int PING_PORT = 3333;
	private ServerSocket serverSocket;
	private ClientConnectable client;
	private static Thread pingServerThread;

	public WiFiServerThread(ClientConnectable frame) {
		super("WiFiServerThread");
		this.client = frame;
		try {
			serverSocket = new ServerSocket(PORT);
			createPingServerThread();
		} catch (IOException e) {
			if(pingServerThread != null)
				pingServerThread.interrupt();
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				//System.out.println("ServerSocket Waiting on port " + PORT);
				Socket socket = serverSocket.accept();
				if(!socket.getInetAddress().getHostAddress().startsWith("192.168.0"))
					return;
				
				WiFiConnectedThread connectedThread = new WiFiConnectedThread(socket, client);
				client.setConnectedThread(connectedThread);
				connectedThread.start();
			} catch (IOException e) {
				//pingServerThread.interrupt();
				e.printStackTrace();
			}
		}
	}

	private void createPingServerThread() {
		pingServerThread = new Thread(new Runnable() {
			private ServerSocket serverSocketPing;
			@Override
			public void run() {
				try {
					serverSocketPing = new ServerSocket(PING_PORT);
					while(true){
						Socket socket = serverSocketPing.accept();	
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			@Override
			protected void finalize() throws Throwable {
				super.finalize();
				serverSocketPing.close();
			}
		});
		pingServerThread.start();
	}
	
	@Override
	protected void finalize() throws Throwable {		
		super.finalize();
		serverSocket.close();
		pingServerThread.interrupt();
	}

}
